/*
* 堆场管理
* */

import 'package:barcode_scan2/model/scan_options.dart';
import 'package:barcode_scan2/platform_wrapper.dart';
import 'package:center_beijing/api/component_api.dart';
import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/custom_floatingAction_buttonLocation.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:left_scroll_actions/left_scroll_actions.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../widgets/custom_select_widget.dart';

class StorageManagement extends StatefulWidget {
  @override
  _StorageManagementState createState() => _StorageManagementState();
}

class _StorageManagementState extends State<StorageManagement>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  List selectList = [];
  CustomLoading loading = CustomLoading.withMessage('提交中...');

  var multiData = {};
  var selectWarehouse = ''; //选择仓库
  var selectArea = ''; //选择分区

  bool listHide = false;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
    var bbq = GlobalConfig.warehouseList;
    LogUtil.d(bbq);
    var tem = Map();
    bbq.forEach((element) {
      if (element['storageLocations'].length > 0) {
        tem[element['warehouseName']] = element['storageLocations'].map((item) {
          return item['storageLocationName'];
        }).toList();
      }
    });
    this.setState(() {
      multiData = tem;
    });
  }

  /*
  * 获取构件详情
  * */
  getCompDetail(compId) async {
    bool have = false;
    for (var i = 0; i < selectList.length; i++) {
      if (selectList[i]['id'] == compId) {
        have = true;
        break;
      }
    }
    if (!have) {
      var result = await getComponentDetail(compId);
      if (result != null) {
        if(result['state'].toString() == '3'){
          Fluttertoast.showToast(msg: '构件已经报废');
        }else if (result['processStatus'].toString() == '3') {
          this.setState(() {
            selectList.add(result);
          });
        } else if (result['processStatus'] < 3) {
          Fluttertoast.showToast(msg: '构件还未生产完成');
        } else {
          Fluttertoast.showToast(msg: '构件已入库');
        }
      }
    }
  }

  submit(temWarehouseId, temAreaId) async {
    loading.show(delay: 30);
    var pass = {
      'compIds': selectList.map((e) {
        return e['id'];
      }).toList(),
      'warehouseId': temWarehouseId,
      'storageId': temAreaId,
    };
    var result = await subStorage(pass);
    loading.dismiss();
    if (result != null && result == '') {
      Fluttertoast.showToast(msg: '入库成功');
      Get.back();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    loading.dismiss();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('堆场管理'),
      ),
      body: Container(
        color: Styles.MainBackgroundColor,
        padding:
            EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        child: Column(
          children: [
            Expanded(
                child: SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    color: Colors.white,
                    padding: EdgeInsets.fromLTRB(Styles.spacing8,
                        Styles.spacing8, Styles.spacing8, Styles.spacing8),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            RichText(
                                text: TextSpan(children: [
                              TextSpan(
                                  text: '已选构件（',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.NormalFont)),
                              TextSpan(
                                  text: selectList.length.toString(),
                                  style: TextStyle(
                                      color: Styles.BlueColor,
                                      fontSize: Styles.NormalFont)),
                              TextSpan(
                                  text: '）',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.NormalFont)),
                            ])),
                            GestureDetector(
                              onTap: () {
                                print('点击');
                                this.setState(() {
                                  listHide = !listHide;
                                });
                              },
                              child: Container(
                                padding: EdgeInsets.fromLTRB(
                                    Styles.spacing4, 0, 0, 0),
                                child: Text(
                                  '查看',
                                  style: TextStyle(
                                      color: Styles.BlueColor,
                                      fontSize: Styles.NormalFont),
                                ),
                              ),
                            )
                          ],
                        ),
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing16, 0, Styles.spacing16, 0),
                            margin: EdgeInsets.fromLTRB(
                                0, Styles.spacing8, 0, Styles.spacing8),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () async {
                                      var result = await Get.toNamed(
                                          RouteConfig.selectComponent,arguments: {'selectList':selectList,'type':'3'});
                                      if (result != null) {
                                        this.setState(() {
                                          selectList = result;
                                        });
                                      }
                                    },
                                    child: Container(
                                      alignment: Alignment.center,
                                      padding: EdgeInsets.fromLTRB(
                                          Styles.spacing16,
                                          Styles.spacing8,
                                          Styles.spacing16,
                                          Styles.spacing8),
                                      decoration: BoxDecoration(
                                          color: Styles.GrayLight,
                                          border: Border.all(
                                              color: Styles.LineColor,
                                              width: 1),
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(4.0.r))),
                                      child: Text(
                                        '搜索构件',
                                        style: TextStyle(
                                            color: Styles.LeftTitleColor,
                                            fontSize: Styles.NormalFont),
                                      ),
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () async {
                                    var result = await QrScan.scan(context);
                                    if (result != null) {
                                      if (result['type'] == 1) {
                                        this.getCompDetail(result['code']);
                                      } else {
                                        showDialog(
                                            barrierDismissible: false,
                                            context: context,
                                            builder: (BuildContext context) {
                                              return AlertDialog(
                                                title: Text('注意'),
                                                content: Text('请扫描构件二维码！'),
                                                actions: <Widget>[
                                                  new Container(
                                                    child: FlatButton(
                                                      child: new Text(
                                                        "确定",
                                                        style: TextStyle(color: Colors.red),
                                                      ),
                                                      onPressed: () {
                                                        Navigator.pop(context);
                                                      },
                                                    ),
                                                  ),

                                                ],
                                              );
                                            });
                                      }
                                    }
                                  },
                                  child: Container(
                                    color: Styles.BlueColor,
                                    padding: EdgeInsets.fromLTRB(
                                        Styles.spacing8,
                                        Styles.spacing8,
                                        Styles.spacing8,
                                        Styles.spacing8),
                                    margin:
                                        EdgeInsets.only(left: Styles.spacing16),
                                    child: Image.asset(
                                      'assets/images/scan.png',
                                      width: 20.w,
                                      height: 20.h,
                                      fit: BoxFit.contain,
                                      color: Colors.white,
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  !listHide
                      ? Column(
                          children: this.selectList.map((item) {
                            return CupertinoLeftScroll(
                              // important, each Row must have different key.
                              // DO NOT use '$index' as Key! Use id or title.
                              key: Key(item.toString()),
                              // left scroll widget will auto close while the other widget is opened and has same closeTag.
                              // 当另一个有相同closeTag的组件打开时，其他有着相同closeTag的组件会自动关闭.
                              closeTag: LeftScrollCloseTag(item.toString()),
                              buttonWidth: 80,
                              child: Container(
                                color: Colors.white,
                                padding: EdgeInsets.fromLTRB(
                                    Styles.spacing8,
                                    Styles.spacing8,
                                    Styles.spacing8,
                                    Styles.spacing8),
                                margin: EdgeInsets.only(top: Styles.spacing8),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(
                                              right: Styles.spacing8),
                                          height: 20.h,
                                          width: 4.w,
                                          color: Styles.BlueColor,
                                        ),
                                        Text(
                                          (item['compKind'] != null &&
                                                  item['compKind']
                                                          ['compKindName'] !=
                                                      null)
                                              ? item['compKind']['compKindName']
                                              : '--',
                                          style: TextStyle(
                                              color: Styles.DetailColor,
                                              fontSize: Styles.Middle16Font),
                                        ),
                                      ],
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          Styles.spacing8,
                                          0,
                                          Styles.spacing8,
                                          0),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            item['code'] != null
                                                ? item['code']
                                                : '--',
                                            style: TextStyle(
                                                color: Styles.DetailColor,
                                                fontSize: Styles.Middle16Font),
                                          ),
                                          Text(
                                            (item['orderInfo'] != null &&
                                                    item['orderInfo']
                                                            ['orderName'] !=
                                                        null)
                                                ? item['orderInfo']['orderName']
                                                : '--',
                                            style: TextStyle(
                                                color: Styles.LeftTitleColor,
                                                fontSize: Styles.NormalFont),
                                          ),
                                          Text(
                                            item['levelPath'] != null
                                                ? (item['levelPath']
                                                        .split('&_&_&'))
                                                    .join('-')
                                                : '--',
                                            style: TextStyle(
                                                color: Styles.LeftTitleColor,
                                                fontSize: Styles.NormalFont),
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              buttons: <Widget>[
                                GestureDetector(
                                  onTap: () {
                                    this.setState(() {
                                      selectList.remove(item);
                                    });
                                    print('删除');
                                  },
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        0, 0, Styles.spacing16, 0),
                                    decoration: BoxDecoration(
                                      color: Styles.RedColor,
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(14.0.r)),
                                    ),
                                    alignment: Alignment.center,
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      children: [
                                        Image(
                                          image: AssetImage(
                                              'assets/images/delete.png'),
                                          width: 16.w,
                                          height: 16.w,
                                          fit: BoxFit.contain,
                                        ),
                                        Text(
                                          '删除',
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: Styles.NormalFont),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                              onTap: () {
                                print('tap row');
                              },
                            );
                          }).toList(),
                        )
                      : Container(),
                  Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                    padding: EdgeInsets.fromLTRB(Styles.spacing8,
                        Styles.spacing8, Styles.spacing8, Styles.spacing8),
                    child: Row(
                      children: [
                        Expanded(
                            child: Container(
                          child: GestureDetector(
                            child: Container(
                              color: Styles.GrayLight,
                              height: Styles.MainSelectRowHeight,
                              child: Padding(
                                padding: EdgeInsets.fromLTRB(
                                    Styles.spacing8, 0, Styles.spacing16, 0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                        child: Text(
                                      (selectWarehouse == '' &&
                                              selectArea == '')
                                          ? '请选择库位'
                                          : (selectWarehouse +
                                              '-' +
                                              selectArea),
                                      style: TextStyle(
                                          fontSize: 17,
                                          color: Styles.DetailColor),
                                      overflow: TextOverflow.ellipsis,
                                    )),
                                    Image(
                                      image: AssetImage(
                                          'assets/images/pull_down.png'),
                                      width: 20,
                                      height: 20,
                                      fit: BoxFit.contain,
                                    )
                                  ],
                                ),
                              ),
                            ),
                            onTap: () {
                              multiData.length > 0
                                  ? Pickers.showMultiLinkPicker(
                                      context,
                                      data: multiData,
                                      // 注意数据类型要对应 比如 44442 写成字符串类型'44442'，则找不到
                                      // selectData: ['c', 'cc', 'cccc33', 'ccc4-2', 44442],
                                      // selectData: ['A仓库', 'a分区'],
                                      columeNum: 2,
                                      suffix: ['', '', '', '', ''],
                                      onConfirm: (value, _) {
                                        this.setState(() {
                                          selectWarehouse = value[0];
                                          selectArea = value[1];
                                        });
                                      },
                                    )
                                  : null;
                            },
                          ),
                        )),
                        GestureDetector(
                          onTap: () async {
                            var result = await QrScan.scan(context);
                            if (result != null) {
                              if (result['type'] == 3) {
                                var bbq = GlobalConfig.warehouseList;
                                var temWarehouse = '';
                                var temArea = '';
                                bool have = false;
                                bbq.forEach((element) {
                                  element['storageLocations'].forEach((item) {
                                    if (item['storageLocationCode'] ==
                                        result['code']) {
                                      temWarehouse = element['warehouseName'];
                                      temArea = item['storageLocationName'];
                                      have = true;
                                    }
                                  });
                                });
                                if (have) {
                                  this.setState(() {
                                    selectWarehouse = temWarehouse;
                                    selectArea = temArea;
                                  });
                                } else {
                                  Fluttertoast.showToast(msg: '库位二维码错误');
                                }
                              } else {
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext context) {
                                      return AlertDialog(
                                        title: Text('注意'),
                                        content: Text('请扫描库位二维码！'),
                                        actions: <Widget>[
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "确定",
                                                style: TextStyle(color: Colors.red),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(context);
                                              },
                                            ),
                                          ),

                                        ],
                                      );
                                    });
                              }
                            }
                          },
                          child: Container(
                            height: Styles.MainSelectRowHeight,
                            color: Styles.BlueColor,
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing16,
                                Styles.spacing8,
                                Styles.spacing16,
                                Styles.spacing8),
                            margin: EdgeInsets.fromLTRB(
                                Styles.spacing16, 0, Styles.spacing16, 0),
                            child: Image.asset(
                              'assets/images/scan.png',
                              width: 20.w,
                              height: 20.h,
                              fit: BoxFit.contain,
                              color: Colors.white,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )),
            Container(
              padding: EdgeInsets.fromLTRB(
                  Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
              child: Container(
                decoration: new BoxDecoration(
                  //背景
                  color: Styles.BlueColor,
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(12.0)),
                ),
                child: FlatButton(
                  disabledColor: Styles.SelectColor,
                  onPressed: () {
                    FocusScope.of(context).requestFocus(new FocusNode());
                    if (selectList.length == 0) {
                      Fluttertoast.showToast(msg: '请添加构件');
                    } else if (selectArea == '') {
                      Fluttertoast.showToast(msg: '请选择库区');
                    } else {
                      showDialog(
                          barrierDismissible: false,
                          context: this.context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: Text('注意'),
                              content: Text('确认入库吗？'),
                              actions: <Widget>[
                                new Container(
                                  child: FlatButton(
                                    child: new Text(
                                      "取消",
                                      style: TextStyle(color: Colors.black),
                                    ),
                                    onPressed: () {
                                      Navigator.pop(context);
                                    },
                                  ),
                                ),
                                new Container(
                                  child: FlatButton(
                                    child: new Text(
                                      "确定",
                                      style: TextStyle(color: Colors.red),
                                    ),
                                    onPressed: () {
                                      var bbq = GlobalConfig.warehouseList;
                                      var temWarehouseId = '';
                                      var temAreaId = '';
                                      bbq.forEach((element) {
                                        element['storageLocations']
                                            .forEach((item) {
                                          if (item['storageLocationName'] ==
                                              selectArea&&selectWarehouse==element['warehouseName']) {
                                            temWarehouseId =
                                                item['warehouseId'].toString();
                                            temAreaId = item['id'].toString();
                                          }
                                        });
                                      });
                                      Navigator.pop(context);
                                      if (temWarehouseId == '' ||
                                          temAreaId == '') {
                                        Fluttertoast.showToast(msg: '请选择库区');
                                      } else if (selectList.length == 0) {
                                        Fluttertoast.showToast(msg: '请添加构件');
                                      } else {
                                        this.submit(temWarehouseId, temAreaId);
                                      }
                                    },
                                  ),
                                ),
                              ],
                            );
                          });
                    }
                  },
                  child: Container(
                    height: Styles.MainButtonHeight,
                    alignment: Alignment.center,
                    child: Text(
                      '确认入库',
                      style: TextStyle(
                          fontSize: Styles.MainButtonTextFont,
                          color: Colors.white),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
